import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import 'package:flutter_application_cyber/pages/Mine/Models/cn_playGoodModel.dart';
import 'package:flutter_application_cyber/tools/cn_aciap_manager.dart';
import 'package:flutter_application_cyber/tools/cn_event_bus.dart';
import 'package:flutter_application_cyber/tools/cn_log_pv_manger.dart';
import '../../tools/cn_click_utils.dart';
import 'package:flutter_application_cyber/tools/cn_event_busUtils.dart';

class CnCoinStorePage extends StatefulWidget {
  const CnCoinStorePage({Key? key, required this.isPodPage}) : super(key: key);
  final bool isPodPage;

  @override
  State<CnCoinStorePage> createState() => _CoinStorePage();
}

class _CoinStorePage extends State<CnCoinStorePage> {
  List goodDataList = [];
  int availableCoins = 0;
  Timer? timer;
  // List<BannerModel> bannerList = [];
  String bannerUrl = '';
  bool isPodPage = false;
  String timeCount = '';
  StreamSubscription? event;

  // late SocketEvent socketEvent;

  @override
  void initState() {
    super.initState();
    CnLogPvManger.stat(
        page: 'purchase',
        subPage: 'subPage',
        terPage: 'terPage',
        broadcasterId: 'broadcasterId');

    event = EventBusUtils.getInstance()?.on().listen((event) {
      if (event.toString() == EventKeys.applePaySuccess) {
        getCoins();
      }
    });

    getCoins();
    _getSearchGoods();
  }

  void applePay(String goodsCode) {
    //原生支付
    var param = {
      'goodsCode': goodsCode,
      'payChannel': 'IAP',
      'source': '',
      'entry': ''
    };
    EasyLoading.show(status: 'loading...');
    CnNetHelper.createRecharge_a(param,
        (HDHResponseData resp, bool result, String msg) {
      CnLogPvManger.stat(
          page: 'createorder',
          subPage: 'subPage',
          terPage: 'terPage',
          broadcasterId: 'broadcasterId');

      EasyLoading.dismiss();
      if (result) {
        CnSCIAPManager manager = CnSCIAPManager.instance;
        manager.applePay(resp.data);
      } else {
        EasyLoading.showError(msg);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/ic_coin_store_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(
                    left: 16, right: 16, top: widget.isPodPage ? 10 : 0),
                child: Column(
                  children: [
                    Container(
                      child: Row(
                        children: [
                          InkWell(
                            onTap: () {
                              Navigator.pop(context);
                            },
                            child: Container(
                              margin: EdgeInsets.only(top: 0, left: 16),
                              width: 30,
                              height: 30,
                              decoration: const BoxDecoration(
                                  image: DecorationImage(
                                image: AssetImage('images/ic_naviBar.png'),
                              )),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 80),
                            child: Image.asset(
                              'images/icon_coins_bg_title.png',
                              width: 110,
                              height: 24,
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                        margin: const EdgeInsets.only(
                            top: 20, bottom: 10, left: 20, right: 20),
                        height: 165,
                        width: 328,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            image: DecorationImage(
                                image:
                                    AssetImage('images/ic_coin_store_top.png'),
                                fit: BoxFit.fill)),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(
                              'images/icon_coins_logo_mine.png',
                              width: 64,
                              height: 54,
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 10),
                              child: Text(
                                '${availableCoins}',
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 30,
                                  color: Color(0xFFEA248F),
                                ),
                              ),
                            )
                          ],
                        )),
                  ],
                ),
              ),
              Expanded(
                  child: Stack(
                children: [
                  Container(
                    constraints: const BoxConstraints(maxHeight: 1000),
                    child: ListView.builder(
                        scrollDirection: Axis.vertical, // 滚动方向
                        itemCount: goodDataList.length,
                        itemBuilder: (context, index) {
                          var model = goodDataList[index];
                          var price = model.price;
                          var exchangeCoin = model.exchangeCoin;
                          var discount = model.discount * 100;

                          return InkWell(
                            onTap: () {
                              if (!CnClickUtils.isClick()) return;
                              //原生支付
                              applePay(model.code);
                            },
                            child: Container(
                              margin: const EdgeInsets.only(
                                  top: 10, left: 20, right: 20),
                              clipBehavior: Clip.hardEdge,
                              decoration: BoxDecoration(
                                  color: const Color(0xFFF6F8FA),
                                  // borderRadius: BorderRadius.circular(14),
                                  boxShadow: const [
                                    BoxShadow(
                                        color: Colors.black38,
                                        offset: Offset(0.0, 1.0),
                                        blurRadius: 1.0,
                                        spreadRadius: 1.0),
                                  ]),
                              // height: 70,
                              child: Column(
                                children: [
                                  Container(
                                    color: Color(0xFFE7ACCC),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        Container(
                                          height: 18,
                                          alignment: Alignment.center,
                                          margin: const EdgeInsets.only(
                                              bottom: 4, right: 16),
                                          // clipBehavior: Clip.hardEdge,
                                          decoration: BoxDecoration(
                                            color: model.tags != ''
                                                ? const Color(0xFFEA248F)
                                                : const Color(0xFFE7ACCC),
                                            borderRadius:
                                                BorderRadius.circular(2),
                                          ),
                                          child: Text(
                                            '  ${model.tags}  ',
                                            style: const TextStyle(
                                                color: Colors.white,
                                                fontSize: 12),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Container(
                                    height: 60,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Container(
                                            margin: const EdgeInsets.only(
                                              left: 16,
                                            ),
                                            child: Row(
                                              children: [
                                                Image.asset(
                                                  'images/icon_coins_logo_mine.png',
                                                  width: 33,
                                                  height: 29,
                                                ),
                                                Container(
                                                  margin: const EdgeInsets.only(
                                                      left: 10),
                                                  child: Text('$exchangeCoin',
                                                      style: const TextStyle(
                                                          fontWeight:
                                                              FontWeight.bold,
                                                          fontSize: 16,
                                                          color: Color(
                                                              0xFF523E0B))),
                                                ),
                                                Row(
                                                  children: [
                                                    Container(
                                                      margin: EdgeInsets.only(
                                                          left: 10, top: 10),
                                                      child: discount > 0
                                                          ? Text(
                                                              '${discount.floor()}',
                                                              style: const TextStyle(
                                                                  fontSize: 11,
                                                                  color: Color(
                                                                      0xFFEA248F)))
                                                          : null,
                                                    ),
                                                    Container(
                                                      margin:
                                                          const EdgeInsets.only(
                                                              right: 10,
                                                              top: 12),
                                                      child: discount > 0
                                                          ? const Text(
                                                              '%off',
                                                              style: TextStyle(
                                                                  fontSize: 11,
                                                                  color: Color(
                                                                      0xFFEA248F)),
                                                            )
                                                          : null,
                                                    ),
                                                  ],
                                                ),
                                              ],
                                            )),
                                        Row(
                                          children: [
                                            Container(
                                              width: 72,
                                              height: 28,
                                              alignment: Alignment.center,
                                              margin: const EdgeInsets.only(
                                                  right: 16),
                                              child: Text(
                                                '\$${price}',
                                                style: const TextStyle(
                                                  color: Color(0xFF523E0B),
                                                  fontSize: 16,
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            )
                                          ],
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ),
                          );
                        }),
                  )
                ],
              ))
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    event?.cancel();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  void getCoins() {
    CnNetHelper.getUserCoins().then((value) {
      setState(() {
        availableCoins = value;
      });
    });
  }

  void _getSearchGoods() async {
    //获取金
    //获取商品列表
    goodDataList.clear();
    EasyLoading.show(status: 'loading...');
    CnNetHelper.getGoodList((List<CnPlayGoodModel> goodList) {
      EasyLoading.dismiss();
      setState(() {
        goodDataList = goodList;
      });
    });
  }
}
